# coding:utf-8
import os
import sys
import time

from PyQt6.QtCore import Qt, QTranslator
from PyQt6.QtGui import QFont
from PyQt6.QtWidgets import QApplication
from qfluentwidgets import FluentTranslator
import schedule
import threading

from service.init_service import DBInit, RefreshStockInit
from views.common.config import cfg
from app import MainWindow


def run_scheduler():
    """在独立线程中运行调度器"""
    while True:
        schedule.run_pending()
        time.sleep(1)


# enable dpi scale
if cfg.get(cfg.dpiScale) != "Auto":
    os.environ["QT_ENABLE_HIGHDPI_SCALING"] = "0"
    os.environ["QT_SCALE_FACTOR"] = str(cfg.get(cfg.dpiScale))

# S1 : 初始化数据库
DBInit().checkAndInitDB()

# S2 : 初始化持有的股票信息
RefreshStockInit().refreshAllHoldStockInfo()

# S3 : 定时刷新股票信息
schedule.every(5).minutes.do(RefreshStockInit().jobRefreshStockInfo)
scheduler_thread = threading.Thread(target=run_scheduler, daemon=True)
run_scheduler()

# create application
app = QApplication(sys.argv)
app.setAttribute(Qt.ApplicationAttribute.AA_DontCreateNativeWidgetSiblings)


# internationalization
locale = cfg.get(cfg.language).value
translator = FluentTranslator(locale)
galleryTranslator = QTranslator()
galleryTranslator.load(locale, "gallery", ".", ":/gallery/i18n")

app.installTranslator(translator)
app.installTranslator(galleryTranslator)

# create main window
w = MainWindow()
w.show()

app.exec()
